package auto.feature;


import auto.common.Login;
import auto.common.Registartion;
import auto.device.Phione;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NotFoundException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;



public class LoginAndRegistartion {

//feature1：执行登录的
    public String login(String accountUser, String passwordUser) throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;
            //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
        } catch (NoSuchElementException e) {
            System.out.println("当前设备没有登录任何账号");
        }


        String result=Login.login(wait,driver,accountUser,passwordUser);
        if(!result.equals("正常")){
            return result;
        }

        System.out.println("登录成功");
        driver.quit();
        return "登录成功";
    }


//feature2：这个方法是用于注册的
    public String registartion(String accountUser, String passwordUser) throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
        } catch (NoSuchElementException e) {

        }

        String result=Registartion.registartion(wait,driver,accountUser,passwordUser);
        if(!result.equals("正常")){
            return result;
        }


        driver.quit();
        return "注册成功";
    }



//feature3:检测二维码刷新的
    public String qrCodeTest(String accountUser, String passwordUser) throws InterruptedException, IOException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
        } catch (NoSuchElementException e) {
            System.out.println("当前设备没有登录任何账号");
        }

        //使用外测服务器进入
        Thread.sleep(500);
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"进入\"`]"))).click();

        /*
        当前服务器选择是不是有问题进行判断
        * */

        //将二维码的页面点出来
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("二维码登录"))).click();

        //如果二维码没有出现就直接返回
        Thread.sleep(1000);
        if (driver.findElements(AppiumBy.accessibilityId("qrcode mast img")).size() > 0) {
            return "二维码无法当前无法显示";
        }


        // 获取旧的二维码
        WebElement oldQr = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain(
                "**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[3]/XCUIElementTypeOther[2]")));

        String oldQrCodeData = decodeQRCode(oldQr);

        // 二维码刷新按钮
        WebElement refreshButton = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeButton[`name == \" 刷新二维码\"`]")));
        refreshButton.click();

        Thread.sleep(5000);

        // 获取新的二维码
        WebElement newQr = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain(
                "**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[3]/XCUIElementTypeOther[2]")));

        String newQrCodeData = decodeQRCode(newQr);

        // 关闭驱动
        driver.quit();

        if (oldQrCodeData.equals(newQrCodeData)) {
            return "两次二维码相同,二维码刷新失败";
        } else {
            return "两次二维码不同，二维码刷新成功";
        }
    }




//下方的方法用于将二维码转换为字符串并返回，如果二维码相同，返回的字符串就是一致的
    private String decodeQRCode(WebElement qrElement) throws IOException {
        String screenshotBase64 = qrElement.getScreenshotAs(OutputType.BASE64);
        byte[] decodedBytes = Base64.getDecoder().decode(screenshotBase64);
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(decodedBytes));

        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;

        try {
            result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            System.out.println("二维码未找到: " + e.getMessage());
            return "";
        } catch (com.google.zxing.NotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}


